<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-button type="primary" @click="showAddRolesForm">添加角色</el-button>
      </el-row>
      <el-table :data="roleslist" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bd-bottom', i1 === 0 ? 'bd-top' : '', 'center']">
              <el-col :span="5">
                <el-tag closable @close="removeRolesTag(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="i2 === 0 ? '' : 'bd-top'">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRolesTag(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeRolesTag(scope.row,item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditForm(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-star-off" size="mini" @click="setPower(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加角色" :visible.sync="addRolesdialogVisible" width="50%" @close="addRolesdialogVisibleClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑角色" :visible.sync="editRolesdialogVisible" width="50%" @close="editRolesdialogVisibleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
  title="分配权限"
  :visible.sync="setPoewrdialogVisible"
  width="50%"
  @close="setPoewrdialogVisibleClosed">
<el-tree
  :data="rightslist"
  show-checkbox
  ref="treeRef"
  node-key="id"
  default-expand-all 
  :default-checked-keys="treeExpandArr"
  :props="defaultProps">
</el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setPoewrdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setPowerCause">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleslist: [],
      addRolesdialogVisible:false,
      addForm:{
         roleName:'',
          roleDesc:''
      },
      addFormRules:{
          roleName: { required: true, message: '请输入角色名称', trigger: 'blur' },
          roleDesc: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      editRolesdialogVisible:false,
      editForm:{},
      editFormRules:{
           roleName: { required: true, message: '请输入角色名称', trigger: 'blur' },
          roleDesc: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      setPoewrdialogVisible:false,
      defaultProps:{
        children:'children',
        label:'authName'
      },
      rightslist:[],
      treeExpandArr:[],
      roleId:''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this, $message.error('查询角色列表失败')
      }
      this.roleslist = res.data
    },
    showAddRolesForm(){
        this.addRolesdialogVisible=true
    },
    addRolesdialogVisibleClose(){
        this.$refs.addFormRef.resetFields()
    },
    addRoles(){
    this.$refs.addFormRef.validate(async valid=>{
        if(!valid) return
       const{data:res}= await this.$http.post('roles',this.addForm)
       if(res.meta.status!==201){
           return this.$message.error('添加失败')
       }
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.addRolesdialogVisible=false
    })
    },
    async showEditForm(id){
        const{data:res}=await this.$http.get('roles/'+id)
        if(res.meta.status!==200){
            return this.$message.error('获取失败')
        }
        this.editForm=res.data
        this.editRolesdialogVisible=true
    },
    editRolesdialogVisibleClose(){
          this.$refs.editFormRef.resetFields()
    },
     editRoles(){
        this.$refs.editFormRef.validate(async valid=>{
        if(!valid){ return this.$message.error('校验失败')}
        const{data:res}= await this.$http.put('roles/'+this.editForm.roleId,this.editForm)
        if(res.meta.status!==200){
            return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getRolesList()
        this.editRolesdialogVisible=false
        })
    },
    async removeRolesById(id){
         const confirmResult = await this.$confirm('请问是否要永久删除该用户', '删除提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != 'confirm') {
        return this.$message.info('已经取消删除')
      }
        const{data:res}=await this.$http.delete('roles/'+id)
 if(res.meta.status!==200){
            return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getRolesList()
    },
    async removeRolesTag(row,rightId){
     const confirmResult= await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!=='confirm'){
          return this.$message.info('取消删除')
        }
        const{data:res}=await this.$http.delete(`roles/${row.id}/rights/${rightId}`)
        if(res.meta.status!==200){
           return this.$message.error('删除失败')
        }
        // 刷新页面 不能直接看出效果
        // this.getRolesList()
        row.children=res.data
    },
    async setPower(row){
      
      this.roleId=row.id
      const {data:res}=await this.$http.get('rights/tree')
      if(res.meta.status!==200){
        return this.$message.error('请求失败')
      }
      this.rightslist=res.data
      this.getTreeExpandArr(row,this.treeExpandArr)
      this.setPoewrdialogVisible=true
    },
    getTreeExpandArr(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getTreeExpandArr(item,arr)
      })
    },
    setPoewrdialogVisibleClosed(){
      this.treeExpandArr=[]
    },
   async setPowerCause(){
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const str=keys.join(',')
      const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:str
      })
      if(res.meta.status!==200){
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.getRolesList();
      this.setPoewrdialogVisible=false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-bottom {
  border-bottom: 1px solid #ccc;
}
.bd-top {
  border-top: 1px solid #ccc;
}
.center {
  display: flex;
  align-items: center;
}
</style>
